package com.tvunetworks.center.device.schedule;

import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.device.constant.CommandConstant;
import com.tvunetworks.center.device.model.TimeLockMsg;
import com.tvunetworks.center.device.service.ReceiverControlService;
import com.tvunetworks.center.device.service.TimeLockMsgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author Ethan
 * @program:
 * @description:
 * @create: 2021/11/15 15:09
 **/
@Slf4j
@RestController
@RequestMapping("/schedule/check/ReceiverStatus")
public class CheckReceiverStatus {

    @Autowired
    private TimeLockMsgService timeLockMsgService;

    @Autowired
    private ReceiverControlService receiverControlService;

    /**
     *  定时任务检查CC这边关闭的R的TimeLock功能,不确定R端那边是否正常关闭.所以check
     *  由于R端收到消息没有执行的概率较小,所以本定时任务执行时间间隔较长
     * @return Result
     * @throws IOException 编译异常
     */
    @PostMapping("/checkReceiver")
    public Result checkReceiver()   {
        List<TimeLockMsg> timeLockMsgs = timeLockMsgService.checkReceiver();
        if (CollectionUtils.isEmpty(timeLockMsgs)) {
            return ResultUtil.success();
        }

        try {
            for (TimeLockMsg timeLockMsg : timeLockMsgs) {
                String id = timeLockMsg.getId();
                String oldEventId = timeLockMsg.getEventId();
                String peerId = timeLockMsg.getPeerId();
                Result<String> command = receiverControlService.command(peerId, CommandConstant.UPLOAD_INFO);
                if (command.getResult() != null) {
                    Map<String, Object> result = JsonUtil.toObject(command.getResult(), Map.class);
                    Integer state = (Integer) result.get("State");
                    String eventId = (String) result.get("Session");
                    if (!state.equals(0)) {
                        //status不等于0表示,R那边因为各种原因关闭TimeLock失败,所以需要重新下发命令去停止
                        if (StringUtils.equals(eventId,oldEventId)){
                            timeLockMsgService.stopTimeLockMsg(eventId, peerId);
                        }
                    }
                    //因为R那边已经正常关闭了TimeLock,所以直接将此数据的ReceiverStatus更改为2
                    timeLockMsgService.updateReceiverTimeLockStatus(id);
                }

            }
        } catch (Exception e) {
            log.error("checkReceiver, timeLockMsg>>>>>>>>> Exception,e", e);
        }
        return ResultUtil.success();
    }

}
